package com.example.gridfsdemo;

import com.example.gridfsdemo.vo.GridFSFileVO;
import com.mongodb.client.gridfs.model.GridFSFile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author susc
 * @title: Controller
 * @projectName gridfs-demo
 * @description: TODO
 * @date 2022/8/2511:09
 */
@RestController
@RequestMapping("gridfs")
@Api("gridfs-demo")
public class GridfsController {

    private GridfsService gridfsService;

    @Autowired
    public GridfsController(GridfsService gridfsService) {
        this.gridfsService = gridfsService;
    }

    @PostMapping(value = "/upload",  consumes = { MediaType.MULTIPART_FORM_DATA_VALUE }, headers = "content-type=multipart/form-data", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
    @ApiOperation("上传附件")
    public String uploadFile(@RequestPart MultipartFile multipartFile) throws IOException {
        gridfsService.uploadFile(multipartFile);
        return "上传成功";
    }

    @GetMapping("/all")
    @ApiOperation(value = "查询文件所有元数据", notes = "查询上传的所有附件信息")
    public List<GridFSFileVO> queryAllFileMetadata(){
        List<GridFSFile> fileList = gridfsService.queryAllFileMetadata();
        List<GridFSFileVO> fsFileVOList = convern(fileList);
        return fsFileVOList;
    }

    @GetMapping("/download/{objectId}")
    @ApiOperation(value = "下载附件", notes = "通过object_id下载附件")
    public void download(@PathVariable("objectId") String objectId, HttpServletResponse response) throws UnsupportedEncodingException {
        gridfsService.download(objectId, response);
    }

    private List<GridFSFileVO> convern(List<GridFSFile> fileList) {
        List<GridFSFileVO> voList = new ArrayList<>();
        if(null != fileList && !fileList.isEmpty()){
            for (GridFSFile gridFSFile : fileList) {
                GridFSFileVO gridFSFileVO = new GridFSFileVO(gridFSFile);
                voList.add(gridFSFileVO);
            }
            return voList;
        }
        return null;
    }
}
